package com.ggy.babybed.socketwork.http;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

/**
 * Created by ggy on 2016/3/31.
 */
public class HttpFactory {
    private static RequestQueue requestQueue;
    private static JSONObject result;

    public static RequestQueue createRequestQueue(Context context){
        if(null == requestQueue){
            requestQueue = Volley.newRequestQueue(context);
        }
        return requestQueue;
    }

    public static JSONObject JsonRequest(String url, Context context){
        result = null;
        JsonObjectRequest request = new JsonObjectRequest(
                url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        result = response;
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                });
        createRequestQueue(context).add(request);
        requestQueue.start();
        return result;
    }

    public static JSONObject JsonRequest(JSONObject object, String url, Context context){
        result = null;
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
                url, object,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        result = response;
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                });
        createRequestQueue(context).add(request);
        requestQueue.start();
        return result;
    }
}
